package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * ClassName: OrderTask
 * Package: IntelliJ IDEA
 *
 * @author 张文豪
 * @description
 * @date 2023/8/19 16:36
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOUtOrder(){
        log.info("定时处理超时订单");
        LambdaQueryWrapper<Orders> orderMapperLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        orderMapperLambdaQueryWrapper.eq(Orders::getStatus,Orders.PENDING_PAYMENT).lt(Orders
        ::getOrderTime,localDateTime);
        List<Orders> orders = orderMapper.selectList(orderMapperLambdaQueryWrapper);
        if(orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("长时间误操作，自动取消订单");
                orderMapper.updateById(order);
            }
        }
        }
        @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("定时处理派送中的订单");
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
            LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-60);
            wrapper.eq(Orders::getDeliveryStatus,Orders.DELIVERY_IN_PROGRESS).le(Orders::getOrderTime,dateTime);
            List<Orders> orders = orderMapper.selectList(wrapper);
            if(orders != null && orders.size() > 0){
                for (Orders order : orders) {
                    order.setDeliveryStatus(Orders.COMPLETED);
                    orderMapper.updateById(order);
                }
            }
        }

}
